Javascript(node.js)承诺异步/等待问题

时间:2018-04-19 14:04:48

标签: javascript node.js promise

new Promise(async (resolve, reject) =>
{
  try
  {
    await new Promise((resolveSec, rejectSec) =>
    {
      setTimeout(function()
      {
        resolveSec('')
      }, 1000);
    }).then(function(val)
    {
      return reject('should reject') //does not stop execution
      //throw('should reject'); //stops execution
    });
    console.log('not here'); //should not get to here
  }
  catch (err)
  {
    console.log('caught error');
  }
}).catch(function(err)
{
  console.log(err);
});

有人可以解释为什么上面的代码不会以“拒绝”结束执行,但它与“throw”一起使用,因为我认为Promise中的“reject”和“throw”都具有相同的功能。

1 个答案:

答案 0 :(得分:0)

原因Sub test1() Dim wb As Workbook Dim ws As Worksheet Dim sourceCell As Range Dim targetSheet As Worksheet Dim fr, lr, nlr, llr As Long Set wb = ThisWorkbook Set ws = wb.Worksheets("Opgørsel") Set sourceCell = ws.Range("D3") Set targetSheet = wb.Worksheets(sourceCell.Text) targetSheet.Range("A1").Value = "1.Altan 150" targetSheet.Range("A1").Font.Bold = 1 targetSheet.Range("A1").Font.Size = 16 targetSheet.Range("A1:K1").Interior.ColorIndex = 27 targetSheet.Range("A3").Value = "1.Altan 250" targetSheet.Range("A3").Font.Bold = 1 targetSheet.Range("A3").Font.Size = 16 targetSheet.Range("A3:K3").Interior.ColorIndex = 27 If ws.Range("H3").Value = 150 Then Do Until targetSheet.Cells(t, 1).Value = "1.Altan 250" lr = t - 1 t = t + 1 Loop ws.Rows("1:10").Copy targetSheet.Rows(lr & ":" & lr).Insert Shift:=xlDown ElseIf ws.Range("H3").Value = 250 Then nlr = targetSheet.Range("A" & 100000).End(xlUp).Row ws.Rows("1:10").Copy targetSheet.Rows(nlr & ":" & nlr).Insert Shift:=xlDown End If targetSheet.Range("A1:K1").Merge llr = targetSheet.Range("A" & 100000).End(xlUp).Row targetSheet.Range("A" & llr & ":K" & llr).Merge targetSheet.Range("N1").Offset(1, 0).Value = Environ("Username") End Sub 结束内部Promises执行,然后由throw语句重新抛出,结束外部Promise的执行。 await但是会​​将外部承诺状态设置为被拒绝reject将结束内部promisee函数的执行,但不会结束外部promisee函数的执行。