如果用户使用 promise,我该如何 "check"?
How do I "check" if user use promise?
我想检查 .then()
是否被用户调用,否则使函数同步,这是我函数的代码
var fun = (ms, unit, asy) => {
var second = 1000,
minute = second * 60,
hour = minute * 60,
day = hour * 24,
week = day * 7,
month = week * 4,
year = day * 365; // or 1000 * 60 * 60 * 24 * 7 * 4 * 12
if ( asy ) {
return new Promise(function (fulfill, reject){
try {
var converted;
switch (unit) {
case 'something':
// Do something
break;
case 'something_else' // etc etc
}
fulfill(converted)
} catch (err) {
reject(err)
}
});
} else {
switch (unit) {
case 'something':
// Do something
break;
case 'something_else' // etc etc
// ...
}
}
}
}
现在它检查 asy
值是否为真,然后将其设置为 asynchronous
但是(如果可能的话)我想将其设置为默认值 synchronous
,只要用户没有调用 .then()
.
这不行,无论调用还是不调用then
,你的功能都已经执行了,所以你不能及时返回。
在异步js编程中使用"classic"回调方式是可行的:
function doSomething(arg1, ... , callback)
{
if(callback !== undefined) {
// Do async way and resolve with the callback
} else {
// Do sync
}
}
函数不可能知道它的 return 值在 return 之后如何使用。该函数已完成(尽管 IO 可能仍在后台 运行)并且在 .then()
被调用时已被 return 编辑。
保持你的 return 类型一致,并且总是 return Promise 如果操作可能是异步的。 Promise .then()
回调已规范化,因此无论 Promise 本身是同步解析还是异步解析,执行顺序都得到保证。
我想检查 .then()
是否被用户调用,否则使函数同步,这是我函数的代码
var fun = (ms, unit, asy) => {
var second = 1000,
minute = second * 60,
hour = minute * 60,
day = hour * 24,
week = day * 7,
month = week * 4,
year = day * 365; // or 1000 * 60 * 60 * 24 * 7 * 4 * 12
if ( asy ) {
return new Promise(function (fulfill, reject){
try {
var converted;
switch (unit) {
case 'something':
// Do something
break;
case 'something_else' // etc etc
}
fulfill(converted)
} catch (err) {
reject(err)
}
});
} else {
switch (unit) {
case 'something':
// Do something
break;
case 'something_else' // etc etc
// ...
}
}
}
}
现在它检查 asy
值是否为真,然后将其设置为 asynchronous
但是(如果可能的话)我想将其设置为默认值 synchronous
,只要用户没有调用 .then()
.
这不行,无论调用还是不调用then
,你的功能都已经执行了,所以你不能及时返回。
在异步js编程中使用"classic"回调方式是可行的:
function doSomething(arg1, ... , callback)
{
if(callback !== undefined) {
// Do async way and resolve with the callback
} else {
// Do sync
}
}
函数不可能知道它的 return 值在 return 之后如何使用。该函数已完成(尽管 IO 可能仍在后台 运行)并且在 .then()
被调用时已被 return 编辑。
保持你的 return 类型一致,并且总是 return Promise 如果操作可能是异步的。 Promise .then()
回调已规范化,因此无论 Promise 本身是同步解析还是异步解析,执行顺序都得到保证。