| 1. |
Asynchronous JavaScript |
|
Answer» A number of Web API features now use asynchronous code for running, especially those that access or fetch a resource from external devices, for instance, retrieving files from the network, accessing some database and returning data to it, accessing a video stream from a webcam, or broadcasting the display to a VR headset. There are two ways in which asynchronous coding can be done in JavaScript:
alert('Button has been clicked!'); let paraElement = document.createElement('p'); paraElement.textContent = 'A new paragraph.'; document.body.appendChild(paraElement); }); The first parameter specifies the type of event to be listened for, while the second specifies a callback function to be called when the event occurs. When we give a callback function as an input to another function, we are merely passing the function's reference; the callback function isn't immediately performed. It is asynchronously "called back" (thus the name) somewhere within the containing function's body. When the time comes, the contained function is in charge of calling the callback function.
return res.json(); }).then(function(json) { let item = json; initialise(item); }).catch(function(e) { console.log('Fetch error: ' + e.message); }); Here, fetch() takes a single argument: the URL of a network resource we wish to fetch and a promise is returned. A promise is an object that represents whether the async operation succeeded or failed. In a sense, it reflects a transitional condition. In essence, it's the browser's way of saying, "I promise to respond as quickly as I can," hence the name "promise." fs.readdir(source, function (error, file) { if (error) { console.log(Problem occurred while finding file: ' + error) } else { file.forEach(function (filename, fileIndex) { console.log(filename) gm(source + filename).size(function (error, value) { if (error) { console.log(Problem occurred while identifying file size: ' + error) } else { console.log(filename + ' : ' + value) aspect = (values.width / values.height) widths.forEach(function (width, widthIndex) { height = Math.round(width / aspect) console.log('resizing ' + filename + 'to ' + height + 'x' + height) this.resize(width, height).write(dest + 'w' + width + '_' + filename, function(error) { if (error) console.log('Problem occurred while writing file: ' + error) }) }.bind(this)) } }) }) } }) |
|