简体   繁体   中英

return a promise from a function in node js

My code checks if an audio file exists in the directory. If it doesn't then it download's the file from a url and then play's it.

    if (condition) {
try {
     if (fs.existsSync(path)) {
    playaudio();
    }
    else {
checkfile().then(function(){
  playaudio();
});
    }
}
catch (err){
console.log(err);
}
  }


function checkfile () {
try {
   if (!fs.existsSync(path)) {
  var file = fs.createWriteStream("ring.wav");
  var request = http.get("http://mp3.com/ring.wav", function(response) {
            response.pipe(file);
          });
    }

} catch(err) {
  console.error(err)
}
}

function playaudio() {
    player.play('ring.wav', function(err){
    if (err) throw err
    })
}

When I run the code it throws an error :

TypeError: checkfile(...).then is not a function

How do I return a promise here?

You need to define a promise first.

let checkfile = new Promise(function(resolve, reject) {
     try {
        if (!fs.existsSync(path)) {
             var file = fs.createWriteStream("ring.wav");

             var request = http.get("http://mp3.com/ring.wav", 
                   function(response) {
                        response.pipe(file);
                        resolve("downloaded");
                 });
        }

   } catch(err) {
        console.error(err)
   }
  });

Now you can use

checkfile.then()....

Here I tried to clean up the code a bit to be a little easier to read. As others have stated, you need to define a promise. Specifically, you need to write a function that RETURNS a promise . If a function returns a promise , you can then use a .then .

Remember, you also need to determine what the promise resolves to in the successful case and in the case of an error, or the rejection case.

MDN Promises: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

I don't have as much context so it's a little bit unclear to me what you will resolve and what you will reject in your checkFile function but I'll try below to give a suggestion on how you may get it to work.

if (condition) {
    try {
        if (fs.existsSync(path)) {
            playaudio();
        } else {
            checkfile().then(function(){
                playaudio();
            });
        }
    } catch (err) {
        console.log(err);
    }
}


function checkfile () {
    try {
        if (!fs.existsSync(path)) {
            var file = fs.createWriteStream("ring.wav");
            var request = http.get("http://mp3.com/ring.wav", function(response){
                response.pipe(file);
            });
        }
    } catch(err) {
          console.error(err)
    }
}

function playaudio() {
    player.play('ring.wav', function(err){
        if (err) throw err
    })
}

Generic example of a function that returns a promise and it's usage:

const somePromiseReturningFunction = function(someParameter) {
    return new Promise(function(resolve, reject) {
        if (someParameter === 'someDesiredString') {
            resolve('Success!');
        } else {
            reject('Error!');
        }
    });
};

somePromiseReturningFunction('someDesiredString')
    .then(function(resolvedValue) {
        console.log(resolvedValue) // prints 'Success!'
    })
    .catch(function(error) {
        console.log(error) // prints 'Error!'
    });

checkFile re-written to return a promise:

function checkfile () {
    return new Promise(function(resolve, reject) {
        try {
            if (!fs.existsSync(path)) {
                var file = fs.createWriteStream("ring.wav");
                var request = http.get("http://mp3.com/ring.wav", function(response){
                    response.pipe(file);
                    resolve();
                });
            }
        } catch(err) {
              reject(err)
        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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