我正在使用async / await和以下代码,在5秒钟后响应const中的setTimeout完成之前,响应不应该为空或为null吗?并且响应不应该返回xyz而不是1吗?
async function test() {
try {
const response = await setTimeout(
function() {
const obj = {};
obj.text = "xyz";
console.log('should console log after 5 seconds')
return obj;
},
5000)
if (response) {
console.log(`response is ${response}`)
console.log(`response.text is ${response.text}`)
}
}
catch(err) {
console.log(err)
}
}
test();
答案 0 :(得分:1)
您必须做出一个承诺来等待setTimeout()。
async function test() {
try {
const response = await new Promise((resolve) => {
setTimeout(
function() {
const obj = {};
obj.text = "xyz";
console.log('should console log after 5 seconds')
return resolve(obj);
},
5000)
});
if (response) {
console.log(`response is ${response}`)
console.log(`response.text is ${response.text}`)
}
}
catch(err) {
console.log(err)
}
}
test();
答案 1 :(得分:1)
为使代码按预期运行,您需要将设置的超时包装在Promise中。检查代码段。无需将其包装在promise中,setTimeout立即返回值,它是计时器的ID值。
async function test() {
try {
const response = await new Promise(function(resolve, reject) {
setTimeout(
function() {
const obj = {};
obj.text = "xyz";
console.log('should console log after 5 seconds')
resolve(obj);
},
5000)
})
if (response) {
console.log(`response is ${response}`)
console.log(`response.text is ${response.text}`)
}
} catch (err) {
console.log(err)
}
}
test();