I want to check if .then()
is called from the user else make the function synchronous, this is the code of my function
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
// ...
}
}
}
}
Now it checks if the asy
value is true and then make it asynchronous
but (if it's possible) I want to make it synchronous
as default, as long as the user doesn't call .then()
.
This can't be done, when then
is called or not, your function is already performed, so you can't go back in time.
It could be possible using the "classic" callback way in async js programming:
function doSomething(arg1, ... , callback)
{
if(callback !== undefined) {
// Do async way and resolve with the callback
} else {
// Do sync
}
}
It's impossible for a function to know how its return value is used after it returned. The function has finished (although the IO may still be running in the background) and returned by the time .then()
is called.
Keep your return types consistent and always return a Promise if there's a chance an operation could be asynchronous. Promise .then()
callbacks are normalized so that the order of execution is guaranteed regardless of whether the Promise itself resolved synchronously or asynchronously.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.