gpt4 book ai didi

javascript - 如何控制台记录 promise ?

转载 作者:行者123 更新时间:2023-12-04 08:01:11 25 4
gpt4 key购买 nike

为什么这段代码不能打印任何东西?
预期结果应该是 async result is: 2 .但它是0。

"use strict"

// run consoleLogPromise
consoleLogPromise( PromiseAChangeCount() );

// a utility which will always console log any promise

async function consoleLogPromise(callback) {
//const res = await callback(); TypeError: callback is not a function
const res = await callback;
console.log("async result is: ", res);
}

// a promise returning function
async function PromiseAChangeCount() {
let count = 0;
await setTimeout(() => {
count = 2
}, 200);
return count;
}

最佳答案

你必须做这样的事情。从PromiseAChangeCount返回一个 promise 解析 setTimeout 中的值,然后你可以在里面等待它 consoleLogPromise

"use strict"

// run consoleLogPromise
consoleLogPromise(PromiseAChangeCount());

// a utility which will always console log any promise

async function consoleLogPromise(callback) {
//const res = await callback(); TypeError: callback is not a function
const res = await callback;
console.log("async result is: ", res);
}

// a promise returning function
async function PromiseAChangeCount() {
let count = 0;
return new Promise((resolve, _) => {
setTimeout(() => {
count = 2;
resolve(count)
}, 200);
})
}

关于javascript - 如何控制台记录 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66453500/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com