Reputation: 5194
My Sequence is:
(Please note I am using the Dropbox API v2)
My Code:
I am using request-promise-native library.
let upload = (req,res) => {
let options = {
method: 'POST',
uri: 'https://content.dropboxapi.com/2/files/upload',
headers: {
'Authorization': 'Bearer Token here',
'Dropbox-API-Arg': "{\"path\": \"/test/"+req.file.originalname+"\",\"mode\": \"overwrite\",\"autorename\": true,\"mute\": false}",
'Content-Type': 'application/octet-stream'
},body: fs.createReadStream(`uploads/${req.file.originalname}`)
};
rp(options)
.then(() => {return _deleteLocalFile(req.file.originalname)})
.then(() => {return _generateShareableLink(req.file.originalname)}) // This makes a POST request to the Dropbox API and should return a link.
.then((shareableLink) => {sendJsonResponse(res, 200, shareableLink)})
.catch(function (err) {sendJsonResponse(res, 500, err)});
};
From my understanding (correct me if Im wrong) promises run in parallel and return a value overtime (whichever promise resolves first). How can I run promises in a specific sequence? Is my implementation of promises within best practices?
Upvotes: 1
Views: 132
Reputation: 68655
Your promises will work in sequence if they are used in chain.
I can suggest you also to use ES8 async/await
features to get more beautiful code
let upload = async (req,res) => {
let options = {
method: 'POST',
uri: 'https://content.dropboxapi.com/2/files/upload',
headers: {
'Authorization': 'Bearer Token here',
'Dropbox-API-Arg': "{\"path\": \"/test/"+req.file.originalname+"\",\"mode\": \"overwrite\",\"autorename\": true,\"mute\": false}",
'Content-Type': 'application/octet-stream'
},body: fs.createReadStream(`uploads/${req.file.originalname}`)
};
try {
const request = await rp(options);
const dlf = await _deleteLocalFile(req.file.originalname);
const shareableLink= await _generateShareableLink(req.file.originalname);
const sendedResponse = await sendJsonResponse(res, 200, shareableLink);
} catch(e) {
await sendJsonResponse(res, 500, err);
}
}
Upvotes: 1