函数过一段时间后返回值时如何处理Promise

时间:2019-02-05 21:47:01

标签: javascript node.js

设置超时时间以调用函数,但是代码需要等待,直到返回未返回

var test = new Promise((resolve,reject)=>{
   resolve(2);
}) 
test.then(r).then(s).then(t).then((tt)=>{
  console.log(tt);
});
function r(r){  
  setTimeout(()=>{
    r=r+1;
    return(r);
  },2000)
}

function s(r){
  r=r+1;
  return(r);
}
function t(r){
  r=r+1;
  return(r);
}

1 个答案:

答案 0 :(得分:0)

您不等待setTimeOut函数完成

var test = new Promise((resolve, reject) => {
    return resolve(2);
})
test.then(r).then(s).then(t).then((tt) => {
    console.log(tt);
});

function r(r) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            r = r + 1;
            return resolve(r);
        }, 2000)
    })
}

function s(r) {
    r = r + 1;
    return r;
}

function t(r) {
    r = r + 1;
    return r;
}