JavaScript异步函数返回promise但也执行该函数。它有点挫败了目的。请解释。还有一种方法可以返回promise而不是仅使用async / await执行(不是Promise)。
https://docs.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url
function wait(ms){
var start = new Date().getTime();
var end = start;
while(end < start + ms) {
end = new Date().getTime();
}
}
const fn = async (value) => {
console.log("start fn ", value)
wait(2000);
console.log("end fn ", value)
return value;
}
const main = async () => {
var promiseForFn = fn(3);
console.log("promiseForFn ", promiseForFn);
var value = await promiseForFn;
console.log("value ", value);
}
main()
或
https://jsfiddle.net/ravilution/woxkossp/
const wait = async(ms) => {
var start = new Date().getTime();
var end = start;
while (end < start + ms) {
end = new Date().getTime();
}
}
const fn = async(value) => {
console.log("start fn ", value)
await wait(2000);
console.log("end fn ", value)
return value;
}
const main = async() => {
var promiseForFn = fn(3);
console.log("promiseForFn ", promiseForFn);
var value = await promiseForFn;
console.log("value ", value);
}
main()
将函数标记为
async
并不是真正异步的原因是答案。感谢@ another-guy
答案 0 :(得分:2)
setTimeout
和Promises
是一些众所周知的函数。async
不使真正异步的原因。它允许您在要等待Promises的地方使用关键字await
。await/async
仅适用于Promise
。它们对于应用于异步代码的命令式(同步)样式表示分支和更复杂的流控制非常有用。尝试以下代码,看看它是如何工作的,希望它有所帮助:
function wait(ms, text) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('complete', text);
resolve({});
}, ms);
});
};
async function doTwoThings() { // This func will return a Promise
await wait(2000, 'BBB'); // - to which you can subscribe with `.then`
await wait(1000, 'AAA'); // - or `await` on within another `async` function.
return 'Both done';
}
doTwoThings()
.then(
result => console.info('Done done done!', result),
err => console.error('Oooops', err)
);
答案 1 :(得分:0)
async关键字只能用于在其代码块中使用await的函数。在你的情况下,&#34;等待&#34;函数是同步的(并阻止事件循环) - 因此不需要异步字。