如何在异步等待中手动触发拒绝

时间:2019-03-24 20:19:34

标签: javascript ecmascript-6 promise

我已经使用Java编写了Promises,并且试图在async-await中实现我的功能。 如何触发将在async-await中的.catch()中捕获的reject()

在promise中,我们有一种方法可以手动触发reject():

const doSomething = (someNumber)=>{
    return new Promise((resolve,reject)=>{
    if (someNumber > 5) {
        resolve('this resolves when someNumber is greater than 5')
    }else{
        reject('this gives a reject when someNumber is not greater than 5')
    }

    })
}

doSomething(7)
.then((infoMessage)=>{
    //this will show
    console.log(infoMessage)
})
.catch((err)=>{
    //this wont show
    console.log(errMessage)
})

doSomething(3)
.then((infoMessage)=>{
        //this wont show
    console.log(infoMessage)
})
.catch((err)=>{
        //this will show
    console.log(errMessage)
})

3 个答案:

答案 0 :(得分:3)

只需抛出错误:

async function rejectMe() {
   throw new Error("rejected!");
}

async function main() {
  await rejectMe();
}

main()
.then(() => {
  console.log("finished!")
})
.catch((e) => {
  console.error(e);
})

答案 1 :(得分:1)

import re def separate_chapters(): pat = re.compile(r'(?<=\[@introS\]).+?(?=\[@introEnd@\])') with open('text1_scott.txt', 'r', encoding="utf-8") as file: for i in pat.findall(file.read()): print(i) inp = input("write text to a file? Y|N: ") if inp != "Y": continue file_name = input("Name of your file: ") with open(file_name, "w", encoding="utf-8") as out_file: out_file.write(i) print("text {} written to a file".format(i)) separate_chapters() 在承诺链中的任何地方都应该这样做。

答案 2 :(得分:0)

具有这种方式:

const doSomething = (someNumber)=>{
if (someNumber > 5) {
    return Promise.resolve('this resolves when someNumber is greater than 5')
}
else{
    return Promisereject('this gives a reject when someNumber is not greater than 5')

} })