Javascript 从setTimeout获取返回值
我只想从Javascript 从setTimeout获取返回值,javascript,return,settimeout,return-value,Javascript,Return,Settimeout,Return Value,我只想从setTimeout中获取返回值,但我得到的是函数的全文格式 函数x(){ setTimeout(y=函数(){ 返回“完成”; }, 1000); 返回y; } console.log(x()); 您无法从传递给setTimeout的函数中获取返回值 调用setTimeout(在您的示例中为x)的函数将完成执行并在传递给setTimeout的函数被调用之前返回 无论您想对获得的值执行什么操作,都需要从传递到setTimeout的函数中执行 在您的示例中,可以这样写: function
setTimeout
中获取返回值,但我得到的是函数的全文格式
函数x(){
setTimeout(y=函数(){
返回“完成”;
}, 1000);
返回y;
}
console.log(x());
您无法从传递给setTimeout
的函数中获取返回值
调用setTimeout
(在您的示例中为x
)的函数将完成执行并在传递给setTimeout
的函数被调用之前返回
无论您想对获得的值执行什么操作,都需要从传递到setTimeout
的函数中执行
在您的示例中,可以这样写:
function x () {
setTimeout(function () {
console.log("done");
}, 1000);
}
x();
最好对函数
x
进行回调,并在超时后发送回调中要执行的任何任务
function x (callback) {
setTimeout(function () {
callback("done");
}, 1000);
}
x(console.log.bind(console)); //this is special case of console.log
x(alert)
你需要为此做出承诺。它们是多填充的,但可以是多填充的: 使用ES2017中的
async
/wait
,如果在async
功能中:
async function() {
const result = await x();
console.log(result); // --> 'done!';
}
我想您需要有标志来知道事件发生或否。setTimeout不返回值。您可以使用变量来检测是否发生事件
var y="notdone";
setTimeout(function () {
y="done";
}, 1000);
您可以在超时发生后访问变量y,以了解是否完成您可以使用Promise和setTimeOut的组合,如下面的示例所示
let f1 = function(){
return new Promise(async function(res,err){
let x=0;
let p = new Promise(function(res,err){
setTimeout(function(){
x= 1;
res(x);
},2000)
})
p.then(function(x){
console.log(x);
res(x);
})
});
}
您的语法是这样的,它将只返回函数。是否要返回“done”?如何返回1000毫秒后调用的函数结果?超时是异步的,因此无法从中返回。(当然可以,但是返回值没有任何用处)最好在函数
x
中获取回调,并使用done调用该函数。const x=async(waitMs)=>newpromise((resolve)=>setTimeout(()=>resolve('done'),waitMs))代码>console.log(等待x(1000))
实际上,在我的示例中,done
是一个需要在setTimeout内返回的承诺。因为我无法在setTimeout内获得返回的deferred.resolve()。怎么样?谢谢你能在问题中给出一个更清晰的代码示例吗?请记住,这不会在函数调用后等待,所以它实际上可能不会发生。例如,在调用x之后添加process.exit,并且“done”将永远不会完成。问题是如何“返回”值。您的函数实际上不返回任何内容,而是执行一个console.log函数。@kaizer1v-这可能是因为不可能返回值(正如我在回答的前两段中解释的那样)。
let f1 = function(){
return new Promise(async function(res,err){
let x=0;
let p = new Promise(function(res,err){
setTimeout(function(){
x= 1;
res(x);
},2000)
})
p.then(function(x){
console.log(x);
res(x);
})
});
}