简体   繁体   English

Javascript Promise,嵌套函数

[英]Javascript promise, nested functions

my question is that im running node.js, and i have 2 functions that needs to be run in a specific order, however they are not returning a promise at this this. 我的问题是,我正在运行node.js,并且我有2个功能需要按特定顺序运行,但是在此情况下它们没有返回承诺。 So i wonder how would i rewrite this to make sure that the main function would return a promise, and if i have nested functions, do i just run the 2nd function from the 1st functions resolve? 因此,我想知道如何重写该代码以确保主函数将返回一个Promise,并且如果我具有嵌套函数,我是否只运行第一个函数解析的第二个函数?

Here is the code: 这是代码:

handleMd5Convert = (file) => {
  fs.readFile(file, (err, buf) => {
    fs.rename(file, directoryPath + md5(buf) + '.mp3', (err) => {
      if (err) console.log('ERROR: ' + err);
    })
  })
})

HandleMd5Convert should be able to to . HandleMd5Convert应该能够。 then()

/Alex /亚历克斯

You should be able to wrap the whole thing in a new Promise() and use resolve() & reject() to handle success and errors: 您应该能够将整个内容包装在new Promise()并使用resolve()reject()处理成功和错误:

handleMd5Convert = (file) => {
  return new Promise((resolve, reject) => {
    fs.readFile(file, (err, buf) => {
      if (err) return reject(err)
      fs.rename(file, directoryPath + md5(buf) + '.mp3', (err) => {
        if (err) return reject(err);
        resolve()
      })
    })
  })
}

handleMd5Convert('test.txt')
.then(() => console.log("done"))
.catch(err => console.log("error:", err))

You can create a promise using new Promise like this: 您可以像下面这样使用new Promise创建一个new Promise

var myPromise = function(resolve) {
    someAsyncMethod(param1, callback(x){
        resolve (x);
    });
}

This way myPromise is able to .then() . 这样, myPromise .then() the promise will be completed only after you call resolve() 仅在您调用resolve()之后,诺言才会完成

myPromise.then(function(result){
    // Your code here...
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM