What is the process for retrieving the result of a promise at a later time?

var screencastId = 'abc'

var a = youtube.get(screencastId);
a.then(function(screencast) {
  // Great, the screencast information is now available.
  console.log(screencast);
});

// How can I access the `screencast` variable below?
connection.beginTransactionAsync().then(function() {
  return connection.queryAsync('INSERT IGNORE INTO Channels SET ?', screencast.channel);
}).then(function() {
  return connection.queryAsync('INSERT INTO Screencasts SET ?', screencast);
}).then(function() {
  var values = tags.map(function(tag) { return [tag]; });
  return connection.queryAsync('INSERT IGNORE INTO Tags VALUES ?', [values])
}).then(function() {
  var values = tags.map(function(tag) { return [screencast.screencastId, tag]; });
  return connection.queryAsync('INSERT INTO ScreencastTags VALUES ?', [values])
}).then(function() {
  return connection.commit();
}).error(function(e) {
  connection.rollback();
  winston.error(e);
});

This code breaks down into two main steps:

  1. Retrieve data about a particular screencast from YouTube via the youtube module.
  2. Save details regarding that screencast in the database.

Both of these processes are asynchronous by nature.

My inquiry is, how do I access the screencast parameter during the second step?

I came across this detailed response, but as someone with limited experience in JavaScript, I'm unsure how to implement it in this scenario.

Answer №1

There are two approaches to solving this issue:

  1. You can create a global variable called screencast, similar to how you have screencastId, which is accessible across all .then calls.
  2. If using a global variable is not feasible, you can also return a new Promise in each .then statement. In the resolve function of the promise, pass the parameter screencast.

Here's an example of the first approach (without being able to test it):

var screencastId = 'abc', screencast

youtube.get(screencastId)
.then(function(sc) {
  screencast = sc;
})

// To maintain the chain
.then(function(){
  return connection.beginTransactionAsync()
})

.then(function() {
  return connection.queryAsync('INSERT IGNORE INTO Channels SET ?', screencast.channel);
}).then(function() {
  return connection.queryAsync('INSERT INTO Screencasts SET ?', screencast);
}).then(function() {
  var values = tags.map(function(tag) { return [tag]; });
  return connection.queryAsync('INSERT IGNORE INTO Tags VALUES ?', [values])
}).then(function() {
  var values = tags.map(function(tag) { return [screencast.screencastId, tag]; });
  return connection.queryAsync('INSERT INTO ScreencastTags VALUES ?', [values])
}).then(function() {
  return connection.commit();
}).error(function(e) {
  connection.rollback();
  winston.error(e);
});

Using a new Promise in the example:

youtube.get(screencastId)
.then(function(sc) {
  return new Promise(function(resolve,reject){
    resolve(sc)
  })
})
.then(function(sc){
  console.log(sc)
})

Answer №2

In my personal view, a good approach would be to declare a global variable called `globalScreencast` and assign the value of the `screencast` in the first step like this:

a.then(function(screencast) {
    // Great! I now have access to screencast information.
    console.log(screencast);
    globalScreencast = screencast;
});

Now, in the subsequent steps, you can easily use the `globalScreencast` variable.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues with excessive firing of JQuery blur and hide functions

I am currently using jQuery v1.11.2 and have set up a basic JSFiddle at this link (http://jsfiddle.net/k1g3upbv/). The layout may not be ideal in JSFiddle due to the integration of Twitter Bootstrap within my project. I quickly put together the JSFiddle, o ...

View content from an external file within an iframe

My goal is to showcase a text file within an iframe that updates automatically every second. To achieve this, I have created a simple function: function refresh() { $("#derek").attr('src', $("#derek").attr('src')); }; The automati ...

Implementing Autocomplete feature in Reactjs with Ant Design Library

In my React application, I created an autocomplete feature with a list of options for the user to select from. Example in Action: Click here to see the demo List of available options: const options = [ { label: "hello", value: "1" ...

Capturing the dynamic server response with nested JSON structures

I am in the process of creating a dynamic data-binding function named assemble that requires two input parameters: server response (JSON) - nested JSON object. instruction set (JSON) - a configuration object that dictates the binding. The Issue: The cur ...

Guide to implement a confirmation box in PHP

I recently set up a Joomla article and integrated the Sourcerer Joomla extension to include JavaScript and PHP in my project. Currently, I am developing a course purchase site where users can buy courses from owners and credits are deducted upon every purc ...

Manipulating datetime format within an input element of type date using Angular's ngModel

I have a date input in my form that is populated from the controller with a string value for 'dateOfDiagnosis'. The format of this string includes the time as well, like this: "2010-09-08T00:00:00" To bind this value to an input field in Angu ...

AngularJS: How to accurately retrieve the offsetTop value upon page initialization

Issue: I am facing difficulty in obtaining the accurate top offset value of a DOM element immediately after the page has loaded. In the project I am currently working on, it is essential to retrieve the offsetTop value of various DOM elements as soon as ...

Swapping out pages with JSON outcomes is a common practice when utilizing ASP.Net MVC in conjunction with JQuery Ajax

When making an ajax call to update an entity and returning the success state in the MVC controller, I encountered a problem that resulted in the page changing with the URL becoming that of the MVC controller action and displaying the JSON result as content ...

Switch to using addresses instead of latitude and longitude coordinates when utilizing the Google Maps API

I am looking to utilize Google Map Markers to indicate the locations where our services are offered. The code I have created using latitude and longitude is functioning properly, however, for my project I need to display city names instead of lat/long ...

Tips on ensuring Angular calls you back once the view is ready

My issue arises when I update a dropdown list on one of my pages and need to trigger a refresh method on this dropdown upon updating the items. Unfortunately, I am unsure how to capture an event for this specific scenario. It seems like enlisting Angular ...

JS Implementation of the Coin Change Algorithm

I've been grappling with this algorithm for the past few days, but unfortunately I haven't been able to come up with a successful solution yet. The available solutions seem to be too advanced for my current level of understanding. This problem mu ...

Using JavaScript to parse JSON and set the value of a DatePicker

I have a text input field in my .cshtml page which is a Date type field. <div class="form-group"> <label for="comments">ETA:</label> <input class="form-control text-box single-line" data-val="true" id="MilestoneETAEdit" name ...

Exploring NodeJS and ExpressJS: Unveiling the significance of routes/index.js

Can you explain the function of this particular file? Does this file handle all the GET and POST requests in a project? If so, wouldn't it become excessively long and complex for larger projects? I encountered an issue when trying to call a POST re ...

Achieving the resolution of a Promise amidst the failure of a separate promise

I need to handle a situation where a promise is resolved regardless of the success or failure of an ajax call. I attempted to use the following code snippet: new Promise(function(resolve, reject) { $.ajax({ url: "nonExistentURL", headers: { ...

During the update from Three.js 68 to 69, an error occurred: Unable to access the property 'boundingSphere' of an undefined object

While upgrading my project from Three.js version 68 to version 69, I encountered an error stating Uncaught TypeError: Cannot read property 'boundingSphere' of undefined on line 6077 of Three.js v69: This error pertains to a function within the T ...

The 404 Page Not Found error is displayed when an Angular JS Encoded URL

I have successfully developed an AngularJS application. The application functions properly with the URL provided below: http://localhost/AngularDemo/about However, when I try to modify the URL as shown below, it redirects me to a 404 error page: http:/ ...

Can a function be called when using ng-options with AngularJS select?

Here is some HTML code <select ng-model="selectedMarker" ng-options="shape.text for shape in Selects('shapes')"> </select> And below is the JavaScript code angular.module('todo', ['ionic']) . ...

Using the select method in JavaScript arrays

Are the functionalities of JavaScript and Ruby similar? array.select {|x| x > 3} Could it be done like this instead: array.select(function(x) { if (x > 3) return true}) ...

The Handsontable popup autocomplete editor is unfortunately truncated by the horizontal scrollbar

I have implemented an autocomplete feature on all columns in my project. However, I am facing an issue where the autocomplete editor gets cut off by the horizontal scrollbar. You can see the problem demonstrated in this jsfiddle link. Here is some code re ...

Implementing Expected Conditions using JavaScript calls in Selenium can greatly improve the reliability and efficiency of

Below is my Python Selenium code that downloads a shapefile of Rio de Janeiro. import time, os from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.support.ui import WebDriverWait from selenium.web ...