我该如何避免使用其他诺言?

我有两个.js文件,例如:

index.js:

app.get("/testing",(req,res) => {
  testAsyncFunction().then((resolvedData) => {
    res.send(resolvedData);
  });
})

和server.js:

const asyncFunction = () => {
  return new Promise((res) => {
    setTimeout(() => {
      res('resolved');
    },3000 )
  })
}

const testAsyncFunction = () => {
  return new Promise(async (res) => {
    const result = await asyncFunction();
    return res(result);
  })
}

这可以按预期工作,但是如果我将testAsyncFunction(这样我就不会创建新的Promise)更改为这样的话:

const testAsyncFunction = async () => {
  const result = await asyncFunction();  
  return result;
}

以及在index.js中:

app.get("/testing",res) => {
  res.send(testAsyncFunction());
})

我得到一个空对象,因为它没有等待3秒,在后一种情况下我会丢失什么?我要避免创建新的Promise只是为了等待另一个诺言。

更新

我将testAsyncFunction更改为以下内容:

const testAsyncFunction = () => {
  asyncFunction().then((result) => {
    return result;
  })  
}

即使具有上述功能。不是一个异步函数,为什么我仍然需要在index.js中等待它。我假设在这种情况下返回的值将不是一个保证,所以这就是我感到困惑的部分。

taidengmeidian 回答:我该如何避免使用其他诺言?

$("#myModalID").modal('toggle'); $('#myModalID').modal('show'); $('#myModalID').modal('hide'); 就是这样,其他方式是反模式。但是,当一个函数返回一个Promise时,您需要等待相同的时间

so that I don't create a new promise

app.get("/testing",async (req,res) => {
  let obj = await testAsyncFunction()
  res.send(obj );
});
,
const testAsyncFunction = async () => {
  const result = await asyncFunction();  
  return result;
}

async函数始终返回承诺。所以这等效于:

const testAsyncFunction = () => {
  return asyncFunction();  
}

我要避免创建新的Promise只是为了等待另一个诺言。

因此,只需使用现有的Promise:

app.get("/testing",(req,res) => {
  asyncFunction().then((resolvedData) => {
    res.send(resolvedData);
  });
})

const asyncFunction = () => {
  return new Promise((res) => {
    setTimeout(() => {
      res('resolved');
    },3000 )
  })
}
本文链接:https://www.f2er.com/2811112.html

大家都在问