There's widespread support for both Promises and async functions in the major browsers. You can find the details in MDN's Promise and async function reference. Also, thanks to Mathias Bynens for updating various parts of the article.
Learn Measure Blog About. We want to hear from you! We are looking for web developers to participate in user research, product testing, discussion groups and more. Apply now to join our WebDev Insights Community. JavaScript Promises: an introduction What's all the fuss about? Events aren't always the best way Promise terminology Promises arrive in JavaScript!
Developers, prepare yourself for a pivotal moment in the history of web development. Maybe you're not even sure what a "promise" is. You'd shrug, but the weight of glittery paper is weighing down on your shoulders.
If so, don't worry about it, it took me ages to work out why I should care about this stuff. You probably want to begin at the beginning. You punch the air! About time right? You've used these Promise things before but it bothers you that all implementations have a slightly different API. You probably want to begin with the terminology. You knew about this already and you scoff at those who are jumping up and down like it's news to them.
Take a moment to bask in your own superiority, then head straight to the API reference. What's all the fuss about? You've probably used events and callbacks to get around this. Events aren't always the best way Events are great for things that can happen multiple times on the same object— keyup , touchstart etc. If HTML image elements had a "ready" method that returned a promise, we could do this: img1. It cannot succeed or fail twice, neither can it switch from success to failure or vice versa.
Promise terminology Domenic Denicola proof read the first draft of this article and graded me "F" for terminology. Despite that, I still get a lot of the terminology mixed up, but here are the basics: A promise can be: fulfilled - The action relating to the promise succeeded rejected - The action relating to the promise failed pending - Hasn't fulfilled or rejected yet settled - Has fulfilled or rejected The spec also uses the term thenable to describe an object that is promise-like, in that it has a then method.
Promises arrive in JavaScript! Here's how you use that promise: promise. Compatibility with other libraries The JavaScript promises API will treat anything with a then method as promise-like or thenable in promise-speak sigh , so if you use a library that returns a Q promise, that's fine, it'll play nice with the new JavaScript promises.
Complex async code made easier Right, let's code some things. Say we want to: Start a spinner to indicate loading Fetch some JSON for a story, which gives us the title, and urls for each chapter Add title to the page Fetch each chapter Add the story to the page Stop the spinner … but also tell the user if something went wrong along the way.
Chaining then isn't the end of the story, you can chain then s together to transform values or run additional async actions one after another.
We could alter our get function to use the JSON responseType , but we could also solve it in promises land: get 'story.
Queuing asynchronous actions You can also chain then s to run async actions in sequence. For example: getJSON 'story. Error handling As we saw earlier, then takes two arguments, one for success, one for failure or fulfill and reject, in promises-speak : get 'story.
Note that the two code examples above do not behave the same, the latter is equivalent to: get 'story. A quick side note but don't make the mistake I first made which is using. So, make sure to use. So, we now have a new promise being returned for each of our values in the array by using the.
What we did here is wrap all our code in a try statement don't worry the catch statement will follow and then call our fs. Because we are doing this for multiple files we can't hard code in the path to the file we want to delete like the example from the docs. So, instead we used the template literals from ES6 to allow us to pass in the name of the file we want to delete into the directory path where it will be located this works because all files are in the same directory.
Following this, regardless if the code errors or succeeds, the callback function passed to fs. We pass the 'err' value through to the callback so we can throw an error should there be one.
If there is no error then we just console log what file was deleted and move on. Now, due to how my code in this project works we actually convert all of the csv files into there own JSON files before merging them into one file which means there's actually 2 files to delete per value, luckily I had the foresight to name them the same thing more like laziness. So, it's just a case of adding in the other file extension I need to delete as another fs. As you can see, in the callback for the second deletion we resolve the promise which in terms is then resolved in the original Promise.
However, we're not done yet; we still have a couple of things to sort out. There was one issue I had to get around, you see for the first three values confirmed, deaths and recovered they are all merged into one file so therefore the original files can be deleted but the forth value dailyReport that is not merged into the main file so we need to keep that one for some of our queries.
The alternative would be to concatMap or sequence the promises of each item. Stack Overflow for Teams — Collaborate and share knowledge with a private group. Create a free Team What is Teams? Collectives on Stack Overflow. Learn more. Saving multiple files using Promise Ask Question. Asked 5 years, 2 months ago. Active 5 years, 2 months ago. Viewed 3k times. Improve this question. Once you return something, the function is done executing.
You will need to replace the first resolve call with the content of the second promise callback — Rob M. Wouldn't that make the two Promise one for roadmap and other for satellite map run sequentially? Add a comment. Anyway within this project, I needed to download several files parse them and merge them into one file.
After this was done instead of just leaving these files lingering about I thought it was best to do some housekeeping and get rid of them. So, I started doing some researching and came across the above method. If you're interested in the full code snippet, please jump to the bottom of the article.
If you're interested in how it works; keep reading. The first thing we need to do is import our packages and then define a function for all our code to live in. But the interesting part is because we are deleting multiple files, we need to immediately return a Promise.
The reason we are doing is because while Promise. Now, you'll see in the code below, I have hard coded in the values I needed to delete as the file names for my project will never change but if you did not know this information or they are dynamic you could get all the files in a directory and loop over them instead of hard-coding the array. Now, we have that bit sorted, let's get into the meaty part.
For each file we need to delete we need to return a new promise so Promise. A quick side note but don't make the mistake I first made which is using.
0コメント